#include "EditSafeDialog.h"

EditSafeDialog::EditSafeDialog(QWidget *parent)
    : QDialog{parent}
{
    setFixedWidth(500);

    setWindowTitle("账户安全");

    QVBoxLayout *layout = new QVBoxLayout(this);

    // 当前账号
    accountLabel = new QLabel("当前账号: user123", this);
    layout->addWidget(accountLabel);

    // 密码输入框
    originalPasswordEdit = new QLineEdit(this);
    originalPasswordEdit->setEchoMode(QLineEdit::Password);
    layout->addWidget(new QLabel("原密码"));
    layout->addWidget(originalPasswordEdit);

    newPasswordEdit = new QLineEdit(this);
    newPasswordEdit->setEchoMode(QLineEdit::Password);
    layout->addWidget(new QLabel("新密码"));
    layout->addWidget(newPasswordEdit);

    confirmPasswordEdit = new QLineEdit(this);
    confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    layout->addWidget(new QLabel("确认密码"));
    layout->addWidget(confirmPasswordEdit);

    // 保存按钮
    saveButton = new QPushButton("修改密码");
    layout->addWidget(saveButton);

    setStyleSheet(R"(
        QDialog {
            background-color: #ffffff;
        }
        QPushButton {
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 5px;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
        QLineEdit, QTextEdit {
            border: 1px solid #ccc;
            padding: 4px;
        }
    )");

    connect(saveButton, &QPushButton::clicked, this, &EditSafeDialog::onSaveButtonClicked);
}

void EditSafeDialog::onSaveButtonClicked()
{
    QString originalPassword = originalPasswordEdit->text();
    QString newPassword = newPasswordEdit->text();
    QString confirmPassword = confirmPasswordEdit->text();

    if (originalPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty())
    {
        QMessageBox::warning(this, "错误", "请填写完整");
        return;
    }

    if (newPassword != confirmPassword)
    {
        QMessageBox::warning(this, "错误", "新密码和确认密码不一致");
        return;
    }

    // 密码校验正则表达式
    QRegularExpression passwordRegex(R"(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$)"); // 至少8个字符，至少包含1个大写字母、1个小写字母和1个数字，可以包含特殊字符

    // 判断密码是否合法
    if (!QRegularExpressionMatch(passwordRegex.match(originalPassword)).hasMatch() || !QRegularExpressionMatch(passwordRegex.match(newPassword)).hasMatch())
    {
        QMessageBox::warning(this, "提示", "密码至少8个字符；至少包含1个大写字母、1个小写字母和1个数字；可以包含特殊字符。");
        return;
    }

    // 发送更新完成信号
    emit safeUpdated(originalPassword, newPassword);

    accept(); // 关闭对话框
}
